<template>
    <el-dialog
        :title="form.id ? '编辑审查清单' : '新增审查清单'"
        :visible.sync="visible"
        width="80%"
        :close-on-click-modal="false"
        :before-close="handleClose"
        append-to-body
        custom-class="rule-edit-dialog"
    >
        <div class="edit-container">
            <!-- 审查清单名称 -->
            <div class="form-section">
                <div class="section-title">审查清单名称</div>
                <el-form ref="form" :model="form" :rules="rules">
                    <el-form-item prop="listName">
                        <el-input
                            v-model="form.listName"
                            maxlength="20"
                            show-word-limit
                            placeholder="请输入审查清单名称"
                        ></el-input>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 规则内容区域 -->
            <div class="rules-section">
                <!-- 左侧规则列表 -->
                <div class="rules-list">
                    <div class="section-header">
                        <div class="left">
                            <span class="title">规则列表</span>
                            <el-tooltip content="管理规则库" placement="top">
                                <i class="el-icon-question"></i>
                            </el-tooltip>
                        </div>
                        <div class="right">
                            <el-button type="primary" size="small" @click="addRule">
                                <i class="el-icon-plus"></i>
                                添加规则
                            </el-button>
                        </div>
                    </div>

                    <!-- 规则列表内容 -->
                    <div v-if="!form.rules || form.rules.length === 0" class="empty-state">
                        <i class="el-icon-document" style="font-size: 48px; color: #909399;"></i>
                        <p class="empty-text">点击右上方"添加规则"从规则库中选择规则</p>
                    </div>
                    <div v-else class="rule-items">
                        <div
                            v-for="(rule, index) in form.rules"
                            :key="index"
                            class="rule-item"
                            :class="{ active: selectedRuleIndex === index }"
                            @click="handleSelectRule(index)"
                        >
                            <div class="rule-item-content">
                                <el-tag
                                    :type="rule.riskLevel === 'high' ? 'danger' : rule.riskLevel === 'medium' ? 'warning' : 'info'"
                                    size="small"
                                    class="risk-tag"
                                >
                                    {{ rule.riskLevel === 'high' ? '高风险' : rule.riskLevel === 'medium' ? '中风险' : '低风险' }}
                                </el-tag>
                                <div class="rule-name">{{ rule.ruleName }}</div>
                            </div>
                            <div class="rule-actions">
                                <el-button
                                    type="text"
                                    class="delete-btn"
                                    @click.stop="removeRule(index)"
                                >
                                    删除
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧规则详情 -->
                <div class="rule-detail">
                    <div class="section-title">规则详情</div>
                    <template v-if="currentRule">
                        <div class="detail-content">
                            <div class="detail-item">
                                <div class="label">规则名称</div>
                                <div class="value title">{{ currentRule.ruleName }}</div>
                            </div>
                            <div class="detail-divider"></div>
                            <div class="detail-item">
                              <div class="label">风险等级</div>
                              <el-tag
                                  :type="currentRule.riskLevel === 'high' ? 'danger' : currentRule.riskLevel === 'medium' ? 'warning' : 'info'"
                                  size="medium"
                                  class="risk-level-tag"
                              >
                                {{ currentRule.riskLevel === 'high' ? '高风险' : currentRule.riskLevel === 'medium' ? '中风险' : '低风险' }}
                              </el-tag>
                            </div>
                            <div class="detail-divider"></div>
                            <div class="detail-item">
                                <div class="label">规则描述</div>
                                <div class="value description">{{ currentRule.ruleDesc }}</div>
                            </div>
                        </div>
                    </template>
                    <div v-else class="empty-detail">
                        <i class="el-icon-document"></i>
                        <p class="empty-text">请在左侧选择规则查看详情</p>
                    </div>
                </div>
            </div>
        </div>

        <div slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>

        <!-- 添加规则弹窗 -->
        <el-dialog
            title="从规则库选择"
            :visible.sync="ruleDialogVisible"
            width="90%"
            :close-on-click-modal="false"
            append-to-body
            custom-class="rule-select-dialog"
        >
            <div class="rule-dialog-content">
                <!-- 左侧规则分组 -->
                <div class="rule-categories">
                    <div class="section-title">规则分组</div>
                    <div class="menu-container">
                        <el-menu
                            :default-active="activeCategory"
                            class="category-menu"
                            @select="handleCategorySelect"
                        >
                            <el-menu-item
                                v-for="item in categoryList"
                                :key="item.id"
                                :index="item.id"
                            >
                                <span>{{ item.title }}</span>
                            </el-menu-item>
                        </el-menu>
                    </div>
                </div>

                <!-- 中间规则列表 -->
                <div class="rule-list-container">
                    <div class="section-title">审查规则</div>
                    <div class="search-bar">
                        <el-input
                            v-model="searchKeyword"
                            placeholder="输入规则名称或相关词进行搜索"
                            prefix-icon="el-icon-search"
                            clearable
                            @input="handleSearch"
                            @keyup.enter.native="handleSearch"
                        >
                            <template slot="append">
                                <el-checkbox v-model="onlyShowSelected">仅看已选</el-checkbox>
                            </template>
                        </el-input>
                    </div>

                    <div class="selected-count" v-if="selectedRules.length > 0">
                        已选择 {{ selectedRules.length }} 条规则
                    </div>

                    <el-table
                        ref="ruleTable"
                        :data="filteredRuleLibrary"
                        @selection-change="handleRuleSelectionChange"
                        @row-click="handleRowClick"
                        highlight-current-row
                        height="400"
                    >
                        <el-table-column
                            type="selection"
                            width="50">
                        </el-table-column>
                        <el-table-column
                            prop="name"
                            label="规则名称"
                            min-width="200">
                            <template slot-scope="scope">
                                <div class="rule-name-cell">
                                    <el-tag size="small" :type="scope.row.riskLevel === 'high' ? 'danger' : scope.row.riskLevel === 'medium' ? 'warning' : 'info'">
                                        {{ scope.row.riskLevel === 'high' ? '高风险' : scope.row.riskLevel === 'medium' ? '中风险' : '低风险' }}
                                    </el-tag>
                                    <span class="rule-name">{{ scope.row.ruleName }}</span>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination-container">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="queryParams.current"
                            :page-sizes="[10, 20, 50, 100]"
                            :page-size="queryParams.size"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total">
                        </el-pagination>
                    </div>
                </div>

                <!-- 右侧规则详情 -->
                <div class="rule-detail">
                    <div class="section-title">规则详情</div>
                    <template v-if="currentRule">
                        <div class="detail-content">
                            <div class="detail-header">
                                <el-tag
                                    :type="currentRule.riskLevel === 'high' ? 'danger' : currentRule.riskLevel === 'medium' ? 'warning' : 'info'"
                                    size="medium"
                                    class="risk-level-tag"
                                >
                                    {{ currentRule.riskLevel === 'high' ? '高风险' : currentRule.riskLevel === 'medium' ? '中风险' : '低风险' }}
                                </el-tag>
                            </div>
                            <div class="detail-item">
                                <div class="label">规则名称</div>
                                <div class="value title">{{ currentRule.ruleName }}</div>
                            </div>
                            <div class="detail-divider"></div>
                            <div class="detail-item">
                                <div class="label">规则描述</div>
                                <div class="value description">{{ currentRule.ruleDesc }}</div>
                            </div>
                        </div>
                    </template>
                    <div v-else class="empty-detail">
                        <i class="el-icon-document"></i>
                        <p class="empty-text">请在左侧选择规则查看详情</p>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="ruleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmAddRules">确 定</el-button>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script>
import { rulelistInfo, rulelistSave, rulelistEdit } from "@/api/rule/list/rulelist.js";
import { leftTreeList, rulePage } from "@/api/rule/rule/rule.js";

export default {
    data() {
        return {
            visible: false,
            form: {
                id: "",
                listName: "",
                rules: []
            },
            rules: {
                listName: [
                    { required: true, message: '请输入审查清单名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ]
            },
            ruleDialogVisible: false,
            ruleLibrary: [], // 规则库数据
            selectedRules: [], // 选中的规则
            searchKeyword: "",
            filteredRuleLibrary: [],
            selectedRuleIndex: -1, // 当前选中的规则索引
            activeCategory: 'all',
            onlyShowSelected: false,
            categoryList: [], // 规则分组列表
            queryParams: {
                current: 1,
                size: 10,
                scenarioId: '',
                keyword: ''
            },
            total: 0,
            currentRule: null, // 当前选中的规则详情
            selectedRuleIds: [], // 用于存储已选规则的ID
        };
    },
    computed: {
        selectedRule() {
            return this.selectedRuleIndex >= 0 ? this.form.rules[this.selectedRuleIndex] : null;
        }
    },
    methods: {
        init(id) {
            this.visible = true;
            this.form = {
                id: "",
                listName: "",
                rules: []
            };

            if (id) {
                rulelistInfo(id).then((resp) => {
                    if (resp.code == 0) {
                        this.$nextTick(() => {
                            this.form = {
                                ...this.form,
                                ...resp.data,
                            };
                            // 如果有规则数据，默认选中第一条
                            if (this.form.rules && this.form.rules.length > 0) {
                                this.handleSelectRule(0);
                            }
                        });
                    } else {
                        this.$msg({
                            message: resp.msg,
                            type: "error",
                        });
                    }
                });
            }
        },
        handleClose() {
            this.$refs.form.resetFields();
            this.visible = false;
        },
        showRuleHelp() {
            this.$alert('规则库中包含所有可用的审查规则，您可以在规则库中管理规则。', '规则库说明', {
                confirmButtonText: '我知道了'
            });
        },
        addRule() {
            this.ruleDialogVisible = true;
            this.searchKeyword = ''; // 清空搜索关键词
            this.selectedRules = []; // 清空临时选择
            // 设置已有规则的选中状态
            this.selectedRuleIds = this.form.rules.map(rule => rule.id);
            this.getCategoryList();
        },
        handleSelectRule(index) {
            this.selectedRuleIndex = index;
            // 更新右侧详情显示
            const selectedRule = this.form.rules[index];
            if (selectedRule) {
                this.currentRule = {
                    ruleName: selectedRule.ruleName,
                    riskLevel: selectedRule.riskLevel,
                    ruleDesc: selectedRule.ruleDesc
                };
            }
        },
        deleteRule() {
            if (this.selectedRuleIndex >= 0) {
                this.removeRule(this.selectedRuleIndex);
                this.selectedRuleIndex = -1;
            }
        },
        removeRule(index) {
            const removedRule = this.form.rules[index];
            this.selectedRuleIds = this.selectedRuleIds.filter(id => id !== removedRule.id);
            this.form.rules.splice(index, 1);
            if (this.selectedRuleIndex === index) {
                this.selectedRuleIndex = -1;
            } else if (this.selectedRuleIndex > index) {
                this.selectedRuleIndex--;
            }
        },
        handleRuleSelectionChange(selection) {
            this.selectedRules = selection;
        },
        confirmAddRules() {
            // 过滤掉已经存在的规则
            const newRules = this.selectedRules.filter(rule => !this.selectedRuleIds.includes(rule.id));
            if (newRules.length > 0) {
                this.form.rules = [...this.form.rules, ...newRules];
            }
            this.ruleDialogVisible = false;
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // 检查是否选择了规则
                    if (!this.form.rules || this.form.rules.length === 0) {
                        this.$message({
                            message: '请至少选择一条规则',
                            type: 'warning'
                        });
                        return;
                    }

                    // 构造提交数据，将规则ID列表单独提取
                    const submitData = {
                        id: this.form.id,
                        listName: this.form.listName,
                        ruleList: this.form.rules.map(rule => rule.id) // 提取规则ID列表
                    };

                    const savePromise = this.form.id ? rulelistEdit(submitData) : rulelistSave(submitData);
                    savePromise.then((resp) => {
                        if (resp.code == 0) {
                            this.$message({
                                type: "success",
                                message: "保存成功！",
                            });
                            this.handleClose();
                            this.$emit('refreshData');
                        } else {
                            this.$message.error(resp.msg || '保存失败');
                        }
                    }).catch(error => {
                        console.error('保存失败:', error);
                        this.$message.error('保存失败');
                    });
                }
            });
        },
        handleCategorySelect(index) {
            this.activeCategory = index;
            this.queryParams.scenarioId = index === 'all' ? '' : index;
            this.queryParams.current = 1;
            this.getRuleList();
        },
        handleSearch() {
            this.queryParams.keyword = this.searchKeyword;
            this.queryParams.current = 1;
            this.getRuleList();
        },
        // 获取规则分组列表
        async getCategoryList() {
            try {
                const res = await leftTreeList();
                if (res.code === 0) {
                    this.categoryList = res.data || [];
                    // 如果有分组数据，默认选中第一个
                    if (this.categoryList.length > 0) {
                        this.activeCategory = this.categoryList[0].id;
                        this.queryParams.scenarioId = this.categoryList[0].id;
                        this.getRuleList(); // 获取第一个分组的规则列表
                    }
                } else {
                    this.$message.error(res.msg || '获取规则分组失败');
                }
            } catch (error) {
                console.error('获取规则分组失败:', error);
                this.$message.error('获取规则分组失败');
            }
        },
        // 获取规则列表
        async getRuleList() {
            try {
                const res = await rulePage(this.queryParams);
                if (res.code === 0) {
                    this.ruleLibrary = res.data.records || [];
                    this.total = Number(res.data.total || 0);
                    this.filterRules();

                    // 设置已选规则的选中状态
                    this.$nextTick(() => {
                        if (this.$refs.ruleTable) {
                            this.ruleLibrary.forEach(rule => {
                                if (this.selectedRuleIds.includes(rule.id)) {
                                    this.$refs.ruleTable.toggleRowSelection(rule, true);
                                }
                            });
                            // 默认显示第一条数据的详情
                            if (this.filteredRuleLibrary.length > 0) {
                                this.currentRule = this.filteredRuleLibrary[0];
                            }
                        }
                    });
                } else {
                    this.$message.error(res.msg || '获取规则列表失败');
                }
            } catch (error) {
                console.error('获取规则列表失败:', error);
                this.$message.error('获取规则列表失败');
            }
        },
        // 表格分页变化
        handleCurrentChange(page) {
            this.queryParams.current = page;
            this.getRuleList();
        },
        // 表格每页条数变化
        handleSizeChange(size) {
            this.queryParams.size = size;
            this.queryParams.current = 1;
            this.getRuleList();
        },
        filterRules() {
            let filtered = this.ruleLibrary;

            // 仅看已选过滤
            if (this.onlyShowSelected) {
                filtered = filtered.filter(rule => this.selectedRuleIds.includes(rule.id));
            }

            this.filteredRuleLibrary = filtered;

            // 在过滤后重新设置选中状态
            this.$nextTick(() => {
                if (this.$refs.ruleTable) {
                    filtered.forEach(rule => {
                        if (this.selectedRuleIds.includes(rule.id)) {
                            this.$refs.ruleTable.toggleRowSelection(rule, true);
                        }
                    });
                }
            });
        },
        // 处理行点击
        handleRowClick(row) {
            this.currentRule = row;
            // 添加高亮效果
            this.$refs.ruleTable.setCurrentRow(row);
        },
    }
};
</script>

<style lang="scss" scoped>
.rule-edit-dialog {
    ::v-deep .el-dialog__body {
        padding: 20px;
    }
}

.edit-container {
    .form-section {
        margin-bottom: 24px;

        .section-title {
            font-size: 14px;
            font-weight: 500;
            color: #1f2329;
            margin-bottom: 8px;
        }
    }

    .rules-section {
        display: flex;
        gap: 20px;
        min-height: 400px;
        max-height: calc(80vh - 200px); // 设置最大高度，确保有足够空间显示其他内容

        .rules-list {
            flex: 1;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            background: #fff;
            display: flex;
            flex-direction: column;
            overflow: hidden; // 防止内容溢出

            .section-header {
                padding: 16px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-bottom: 1px solid #e4e7ed;

                .left {
                    display: flex;
                    align-items: center;
                    gap: 8px;

                    .title {
                        font-size: 16px;
                        font-weight: 500;
                        color: #1f2329;
                    }

                    .el-icon-question {
                        color: #909399;
                        cursor: pointer;
                    }
                }
            }

            .rule-items {
                flex: 1;
                overflow-y: auto;
                padding: 16px;

                &::-webkit-scrollbar {
                    width: 6px;
                }

                &::-webkit-scrollbar-thumb {
                    background: #dcdfe6;
                    border-radius: 3px;
                }

                &::-webkit-scrollbar-track {
                    background: #f5f7fa;
                }

                .rule-item {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 12px 16px;
                    border-radius: 4px;
                    background: #f9f9f9;
                    margin-bottom: 8px;
                    cursor: pointer;
                    transition: all 0.3s;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    &:hover {
                        background: #f0f2f5;
                    }

                    &.active {
                        background: #e8f3ff;
                        border-color: #a3d0fd;
                    }

                    .rule-item-content {
                        display: flex;
                        align-items: center;
                        gap: 8px;
                        flex: 1;
                        min-width: 0;

                        .risk-tag {
                            flex-shrink: 0;
                        }

                        .rule-name {
                            font-size: 14px;
                            color: #1f2329;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                        }
                    }

                    .rule-actions {
                        flex-shrink: 0;
                        opacity: 0;
                        transition: opacity 0.3s;

                        .delete-btn {
                            color: #f56c6c;
                            padding: 0;
                            font-size: 13px;

                            &:hover {
                                color: #f78989;
                            }
                        }
                    }

                    &:hover .rule-actions {
                        opacity: 1;
                    }
                }
            }
        }

        .rule-detail {
            flex: 1;
            border: 1px solid #e4e7ed;
            border-radius: 4px;
            padding: 16px;
            background: #fff;

            .section-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 16px;

                .title {
                    font-size: 14px;
                    font-weight: 500;
                    color: #1f2329;
                }

                .delete-btn {
                    color: #f56c6c;
                }
            }

            .detail-content {
                .detail-item {
                    margin-bottom: 16px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .label {
                        font-size: 14px;
                        color: #909399;
                        margin-bottom: 8px;
                    }

                    .value {
                        font-size: 14px;
                        color: #1f2329;
                        line-height: 1.6;
                    }
                }
            }
        }
    }
}

.empty-state,
.empty-detail {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    background: #f9f9f9;
    border-radius: 4px;
    margin: 16px;

    i {
        margin-bottom: 16px;
    }

    .empty-text {
        color: #909399;
        font-size: 14px;
        margin: 0;
    }
}

.rule-select-dialog {
    ::v-deep .el-dialog__body {
        padding: 0;
        height: calc(90vh - 108px);  // 减去头部和底部的高度
    }

    .rule-dialog-content {
        height: 100%;
        display: flex;

        .rule-categories {
            width: 280px;
            border-right: 1px solid #e4e7ed;
            background: #f5f7fa;
            display: flex;
            flex-direction: column;
            height: 100%;

            .section-title {
                padding: 16px;
                font-size: 14px;
                font-weight: 500;
                color: #1f2329;
                border-bottom: 1px solid #e4e7ed;
                background: #f5f7fa;
            }

            .menu-container {
                flex: 1;
                overflow-y: auto;

                &::-webkit-scrollbar {
                    width: 6px;
                }

                &::-webkit-scrollbar-thumb {
                    background: #dcdfe6;
                    border-radius: 3px;
                }

                &::-webkit-scrollbar-track {
                    background: #f5f7fa;
                }

                ::v-deep .el-menu {
                    border-right: none;
                    height: 100%;
                }
            }
        }

        .rule-list-container {
            width: 960px;
            border-right: 1px solid #e4e7ed;
            background: #fff;
            display: flex;
            flex-direction: column;
            height: 100%;

            .section-title {
                padding: 16px;
                font-size: 14px;
                font-weight: 500;
                color: #1f2329;
                border-bottom: 1px solid #e4e7ed;
            }

            .search-bar {
                padding: 16px;
                border-bottom: 1px solid #e4e7ed;
            }

            .selected-count {
                padding: 8px 16px;
                color: #606266;
                font-size: 14px;
                border-bottom: 1px solid #e4e7ed;
            }

            ::v-deep .el-table {
                flex: 1;
                overflow: hidden;

                .el-table__inner-wrapper {
                    height: 100%;
                }

                .el-table__body-wrapper {
                    height: calc(100% - 40px) !important;
                    overflow-y: auto;
                }
            }

            .pagination-container {
                padding: 16px;
                border-top: 1px solid #e4e7ed;
            }
        }

        .rule-detail {
            width: 400px;
            background: #fff;
            display: flex;
            flex-direction: column;
            height: 100%;
            border-radius: 4px;
            border: 1px solid #e4e7ed;

            .section-title {
                padding: 16px 20px;
                font-size: 16px;
                font-weight: 500;
                color: #1f2329;
                border-bottom: 1px solid #e4e7ed;
                background: #fff;
            }

            .detail-content {
                flex: 1;
                padding: 0;
                overflow-y: auto;

                .detail-header {
                    padding: 20px;
                    background: #fafafa;
                    border-bottom: 1px solid #e4e7ed;

                    .risk-level-tag {
                        font-size: 13px;
                        padding: 0 12px;
                        height: 28px;
                        line-height: 28px;
                        border-radius: 4px;
                    }
                }

                .detail-item {
                    padding: 20px;

                    .label {
                        font-size: 13px;
                        color: #909399;
                        margin-bottom: 8px;
                    }

                    .value {
                        color: #1f2329;
                        line-height: 1.6;

                        &.title {
                            font-size: 15px;
                            font-weight: 500;
                            line-height: 1.4;
                        }

                        &.description {
                            font-size: 14px;
                            white-space: pre-wrap;
                            color: #4e5969;
                        }
                    }
                }

                .detail-divider {
                    height: 1px;
                    background-color: #e4e7ed;
                    margin: 0;
                }
            }

            .empty-detail {
                flex: 1;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                color: #909399;
                padding: 40px 0;

                i {
                    font-size: 48px;
                    margin-bottom: 16px;
                    color: #c0c4cc;
                }

                .empty-text {
                    font-size: 14px;
                    margin: 0;
                    color: #909399;
                }
            }
        }
    }
}

::v-deep .el-dialog {
    margin: 5vh auto 0 !important;
    display: flex;
    flex-direction: column;
    height: 90vh !important;
    width: 80% !important;
    min-width: 1600px !important;

    .el-dialog__body {
        flex: 1;
        overflow: hidden;
    }

    .el-dialog__footer {
        border-top: 1px solid #e4e7ed;
        background: #fff;
        padding: 16px 20px;
    }
}
</style>

